package cn.jly.akka.first

import akka.actor.{Actor, ActorRef, ActorSystem, Props}

import scala.io.StdIn

/**
 * mailbox继承了runnable接口，是一个线程
 * 当收到消息时调用actor的receive方法
 *
 * private[akka] abstract class Mailbox(val messageQueue: MessageQueue)
 * extends ForkJoinTask[Unit] with SystemMessageQueue with Runnable {
 */
object FirstAkkaDemo {
  def main(args: Array[String]): Unit = {
    // 创建actorSystem
    val actorSystem: ActorSystem = ActorSystem("actorSystem")
    // 创建actorRef，其中Props[HelloActor]通过反射创建HelloActor对象
    val helloActorRef: ActorRef = actorSystem.actorOf(Props[HelloActor], "helloActor")

    import scala.util.control.Breaks._
    breakable {
      while (true) {
        // 接受输入
        val input: String = StdIn.readLine
        // 发送消息
        helloActorRef ! input
        // 退出循环
        if ("exit".equals(input))
          break()
      }
    }
  }
}

// 定义actor
class HelloActor extends Actor {
  // 重写receive方法
  override def receive: Receive = {
    case "hxfz" => println("收到hxfz")
    case "exit" => {
      println("收到退出指令")
      // 停止actorRef
      context.stop(self)
      // 关闭actorSystem
      context.system.terminate()
    }
    case _ => println("匹配出错")
  }
}


